package com.example.takeaway.websocket;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.takeaway.websocket.message.AbstractMessage;
import com.example.takeaway.websocket.message.MessageType;
import com.example.takeaway.websocket.message.NoticeMessage;
import com.example.takeaway.websocket.message.OrderNewMessage;

import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;

/**
 * @author 邢晨旭
 * {@code @date} 2023/10/26
 */
public class WsMessageDecoder implements Decoder.Text<AbstractMessage> {
    /**
     * 解码
     *
     * @param s 客户端发送的消息
     * @return 解码后的消息
     * @throws DecodeException 解码异常
     */
    @Override
    public AbstractMessage decode(String s) throws DecodeException {
        AbstractMessage message = null;
        JSONObject object = JSON.parseObject(s);
        MessageType type = MessageType.get(object.getInteger("type"));
        switch (type) {
            case ORDER_NEW:
                message = JSON.parseObject(s, OrderNewMessage.class);
                break;
            case NOTICE:
                message = JSON.parseObject(s, NoticeMessage.class);
                break;
            default:
                break;
        }
        return message;
    }

    /**
     * 判断消息是否可以解码
     *
     * @param s 客户端发送的消息
     * @return 是否可以解码
     */
    @Override
    public boolean willDecode(String s) {
        JSONObject object = JSON.parseObject(s);
        Integer type = object.getInteger("type");
        return MessageType.isMessageType(type);
    }

    @Override
    public void init(EndpointConfig endpointConfig) {

    }

    @Override
    public void destroy() {

    }
}
